package index

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/public"
	"gorm.io/gorm"
)

type IndexService struct {
}

// VerifyDeviceCode 验证设备码
// Author: [g-qs](https://github.com/g-qs)
func (i *IndexService) VerifyDeviceCode(info *public.BluetoothDeviceRecord) (status uint, err error) {
	var byDeviceCode public.BluetoothDeviceRecord
	var byPhone public.BluetoothDeviceRecord
	byDcErr := global.GVA_DB.Where("deviceID = ?", info.DeviceID).First(&byDeviceCode).Error
	byPhErr := global.GVA_DB.Where("phone = ?", info.Phone).First(&byPhone).Error
	if errors.Is(byDcErr, gorm.ErrRecordNotFound) && errors.Is(byPhErr, gorm.ErrRecordNotFound) {
		return 3, errors.New("藍牙設備碼記錄不存在！")
	}
	if byDeviceCode.DeviceID == info.DeviceID && byPhone.Phone == info.Phone {
		status = 1
	} else {
		status = 2
	}
	return
}

// SaveDeviceCode 保存设备码
// Author: [g-qs](https://github.com/g-qs)
func (i *IndexService) SaveDeviceCode(info *public.BluetoothDeviceRecord) (err error) {
	err = global.GVA_DB.Create(info).Error
	return
}
